#!/usr/bin/python
# encoding: utf-8
'''
@File    :   code.py
@Time    :   2020/03/11 21:54:19
@Author  :   fangkaijin 
@Version :   1.0
@Contact :   fangkaijin@gmail.com
@License :   杭州移动互联
@Desc    :   None
'''

# 导入库包

import sys, os

import threading, time, random

#新线程执行方法
def loop():
    print('子线程 %s 开始执行' % (threading.current_thread().name))
    n = 0
    while n<5 :
        n += 1
        print('子线程 %s ---- %s' % (threading.current_thread().name, n))
        time.sleep(1)
    print('子线程 %s 执行结束' % (threading.current_thread().name))

print('线程 %s 正在执行' % threading.current_thread().name)
t = threading.Thread(target= loop, name='LoopThread')
t.start()
t.join()
print('线程 %s 执行结束' % (threading.current_thread().name))

#线程锁
lock = threading.Lock()
balance = 0
def change_it(n):
    global balance
    balance += n
    balance -= n
    print('balance 的值 %d .' % (balance))

def run_thread(n):
    for i in range(10000):
        #加锁
        lock.acquire()
        try:
            change_it(i)
        finally:
            #释放锁
            lock.release()

t1 = threading.Thread(target=run_thread, args=(5,))
t2 = threading.Thread(target=run_thread, args=(8,))
t1.start()
t2.start()
t1.join()
t2.join()
print(balance)

#ThreadLocal
class Student(object):
    def __init__(self, name):
        self.name = name

    def printName(self):
        print('该学生的名字 %s .' % (self.name))

    def getName(self):
        return self.name

local = threading.local()

def process_student():
    std = local.student
    print('Hello, %s (in %s)' % (std.getName(), threading.current_thread().name))

def process_thread(name):
    s = Student(name)
    s.printName()
    local.student = s
    process_student()

if __name__ == '__main__':
    t1 = threading.Thread(target=process_thread, name='student1', args=('小黑',))
    t2 = threading.Thread(target=process_thread, name='student2', args=('小白',))
    t1.start()
    t2.start()
    t1.join()
    t2.join()
